var c = document.getElementById('c'),
    ctx = c.getContext('2d'),
    drawingSurfaceImageData, //用户擦除光标的canvas快照
    blinkCursorInterval,
    line,
    cursor = new TextCursor();

var BLINK_ON = 300,
    BLINK_OFF = 700;

//事件绑定
c.addEventListener('mousedown', handleMousedown, false);
document.addEventListener('keydown', handleDocKeydown, false);
document.addEventListener('keypress', handleDocKeyPerss, false);

function handleMousedown(e) {
    var targetBound = e.target.getBoundingClientRect();
    var loc = {
        x: e.clientX - targetBound.left,
        y: e.clientY - targetBound.top
    };
    // var fontHeight = ctx.measureText('W').width;
    // fontHeight += fontHeight / 6;
    line = new TextLine(loc.x, loc.y);
    moveCursor(loc.x, loc.y);
}

function handleDocKeydown(e) {
    if(e.keyCode === 8 || e.keyCode === 13) { //即Backspace  和 enter 键。
        e.preventDefault(); //退格键 和 回车键 都有默认事件，这里阻止掉。
    }
    if(e.keyCode === 8) { //退格键 做单独处理
        ctx.save();
        line.erase(ctx, drawingSurfaceImageData);
        line.removeCharacterBeforeCaret();
        moveCursor(line.left + line.getWidth(ctx), line.bottom);
        line.draw(ctx);
        ctx.restore();
    }
}

function handleDocKeyPerss(e) {
    var key = String.fromCharCode(e.which); //获取字符按键的字符，功能按键不会产生key，接收一个unicode值
    if(e.keyCode !== 8 && !e.ctrlKey && !e.metaKey) {
        e.preventDefault();
        ctx.save();
        line.erase(ctx, drawingSurfaceImageData);
        line.insert(key);
        moveCursor(line.left + line.getWidth(ctx), line.bottom);
        ctx.shadowColor = 'rgba(0, 0, 0, .5)';
        ctx.shadowOffsetX = 1;
        ctx.shadowOffsetY = 1;
        ctx.shadowBlur = 2;
        line.draw(ctx);
        ctx.restore();
    }
}

/**
 * 形成光标闪烁效果
 */
function blinkCursor () {
    blinkCursorInterval = setInterval( function() {
        cursor.erase(ctx, drawingSurfaceImageData);
        setTimeout( function() {
            cursor.draw(ctx, cursor.left, cursor.top + cursor.getHeight(ctx) / 2);
        }, BLINK_ON);
    }, BLINK_OFF + BLINK_ON);
}

/**
 * 根据传入坐标对象绘制光标
 * @param {Object} loc {x: 当前鼠标位置, y: 当前鼠标位置}
 */
function moveCursor(x, y) {
    cursor.erase(ctx, drawingSurfaceImageData);
    saveDrawingSurface();
    cursor.draw(ctx, x, y);

    if(!blinkCursorInterval) blinkCursor();
}

/**
 * 保存canvas快照
 */
function saveDrawingSurface() {
    drawingSurfaceImageData = ctx.getImageData(0, 0, c.width, c.height);
}

/**
 * 绘制背景框
 */
function drawBackground (ctx) {
    ctx.save();
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.rect(0, 0, c.width, c.height);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
}

//初始化 ·····················
ctx.font = '64px Arial';
cursor.fillStyle = '#000';
ctx.fillStyle = '#00bbff';
ctx.strokeStyle = '#222';
ctx.lineWidth = 2;
drawBackground(ctx);
saveDrawingSurface();